package com.example.hotel_lxy.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.CustomerBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.ZeroSpSourceBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialog;
import com.example.hotel_lxy.ui.dialog.DialPhoneDialog;
import com.example.hotel_lxy.ui.fragment.FragmentMarketing;
import com.example.hotel_lxy.ui.main.CalendarActivity;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ysxsoft.common_base.adapter.BaseQuickAdapter;
import com.ysxsoft.common_base.adapter.BaseViewHolder;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.frame.list.IListAdapter;
import com.ysxsoft.common_base.base.frame.list.ListManager;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.ysxsoft.common_base.view.widgets.MultipleStatusView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 客户
 */
@Route(path = "/main/CustomerActivity")
public class CustomerActivity extends BaseActivity implements IListAdapter<CustomerBean.DataBean.ListBean> {

    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.line_date)
    LinearLayout lineDate;
    @BindView(R.id.rb_banquet)
    RadioButton rbBanquet;
    @BindView(R.id.rb_zero)
    RadioButton rbZero;
    @BindView(R.id.rb_order)
    RadioGroup rbOrder;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;
    ListManager<CustomerBean.DataBean.ListBean> manager;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_time)
    TextView endTime;
    int type = 1;
    @BindView(R.id.director)
    TextView director;
    @BindView(R.id.back)
    ImageView back;
    int type_date = 1;
    private String begin_time = "";
    private String end_time = "";
    private String director_id = "";

    public static void start() {
        ARouter.getInstance().build(ARouterPath.getCustomerActivity())
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_customer;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doWork() {
        super.doWork();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);  //事件的注册
        }else {
            EventBus.getDefault().unregister(this); //解除注册
            EventBus.getDefault().register(this);  //事件的注册
        }

        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());//获取当前时间
        String currentDate = simpleDateFormat.format(date);
//        startTime.setText(currentDate);
//        endTime.setText(currentDate);
//        begin_time = ""+currentDate;
//        end_time = ""+currentDate;
        rbOrder.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_banquet) {//宴会
                    rbOrder.setBackgroundDrawable(getResources().getDrawable(R.mipmap.icon_order_unprocessed));
                    boolean banquetclient = JurisdictionUtils.getBanquetclient(CustomerActivity.this);
                    if(!banquetclient){
                        director_id= SPUtils.get(CustomerActivity.this, "id", "").toString();
                        showDataView();
                    }
                    request(1);
                } else if (checkedId == R.id.rb_zero) {//零点
                    rbOrder.setBackgroundDrawable(getResources().getDrawable(R.mipmap.icon_order_all));
                    boolean zeroclient = JurisdictionUtils.getZeroclient(CustomerActivity.this);
                    if(!zeroclient){
                        director_id= SPUtils.get(CustomerActivity.this, "id", "").toString();
                        showDataView();
                    }
                    request(1);
                }
            }
        });

        director_id= SPUtils.get(CustomerActivity.this, "id", "").toString();

        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                request(1);
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

        showDataView();
        showView();
        director.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rbBanquet.isChecked()) {
                    boolean banquetclient = JurisdictionUtils.getBanquetclient(CustomerActivity.this);
                    if(!banquetclient){
                        ToastUtils.longToast(CustomerActivity.this,"当前账号没有操作权限哦");
                        return;
                    }
                } else if (rbZero.isChecked()) {
                    boolean zeroclient = JurisdictionUtils.getZeroclient(CustomerActivity.this);
                    if(!zeroclient){
                        ToastUtils.longToast(CustomerActivity.this,"当前账号没有操作权限哦");
                        return;
                    }
                }
                DataSelectionDialog.show(CustomerActivity.this, null, Api.POST_ZERO_VIEW).setListener(new DataSelectionDialog.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        director_id = id + "";
                        director.setText("" + name);
                        showLoadingDialog();
                        request(1);
                    }
                });
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void showView() {
        manager = new ListManager(this);
        manager.init(getWindow().findViewById(android.R.id.content));
        manager.getAdapter().setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        manager.getAdapter().setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                request(manager.nextPage());
            }
        }, recyclerView);

        request(1);
    }

    private void showDataView() {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_VIEW)
                .addHeader("flag", SPUtils.get(CustomerActivity.this, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户经理onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户经理onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(CustomerActivity.this,"token","");
                            Intent intent = new Intent(CustomerActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        if (beanBean.getCode().equals("0")) {
                            for (int i = 0; i <zeroSpSourceBean.getData().getList().size() ; i++) {
                                ZeroSpSourceBean.DataBean.ListBean listBean = zeroSpSourceBean.getData().getList().get(i);
                                if(director_id.equals(""+listBean.getId())){
                                    director.setText("" + listBean.getUsername());
                                    break;
                                }
                            }
                        }
                    }
                });
    }
    public static String hidePhone(Context context, String phone) {

        if (!TextUtils.isEmpty(phone) && phone.length() == 11) {

            phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);

        } else {

            //Toast.makeText(context, "手机号格式不正确", Toast.LENGTH_SHORT).show();

        }

        return phone;

    }

    @Override
    public int getItemLayoutId() {
        return R.layout.item_customer_activity;
    }

    @Override
    public void request(int page) {
        if (rbBanquet.isChecked()) {
            type = 1;

        } else if (rbZero.isChecked()) {
            type = 2;

        }
        String token = SPUtils.get(CustomerActivity.this, "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_CLIENTINDEX)
                .addHeader("flag", token)
                .addParams("page", page + "")
                .addParams("type", type + "")
                .addParams("manager_id", director_id)
                .addParams("search", editSearch.getText().toString())
                .addParams("begin_time", begin_time)
                .addParams("end_time", end_time)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户onError   " + e.getMessage());
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                manager.releaseRefresh();
                                hideLoadingDialog();
                                ToastUtils.shortToast(CustomerActivity.this,""+e.getMessage());
                            }
                        });

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        manager.releaseRefresh();
                        Log.e("TAG", "客户onResponse   " + response);
                        hideLoadingDialog();
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("4")) {
                            SPUtils.put(CustomerActivity.this, "token", "");
                            Intent intent = new Intent(CustomerActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        if (beanBean.getCode().equals("0")) {
                            CustomerBean customerBean = JsonUtils.parseByGson(response, CustomerBean.class);
                            if(page==1){
                                manager.resetPage();
                            }
                            manager.setData(customerBean.getData().getList());
                        }
                    }
                });
    }

    @Override
    public void fillView(BaseViewHolder helper, CustomerBean.DataBean.ListBean s) {
        TextView text_username = helper.itemView.findViewById(R.id.text_username);
        TextView text_mobile = helper.itemView.findViewById(R.id.text_mobile);
        TextView text_num = helper.itemView.findViewById(R.id.text_num);
        TextView text_money = helper.itemView.findViewById(R.id.text_money);
        TextView text_manager = helper.itemView.findViewById(R.id.text_manager);
        LinearLayout line_money = helper.itemView.findViewById(R.id.line_money);
        text_username.setText("" + s.getName());
//        text_mobile.setText(hidePhone(CustomerActivity.this, s.getMobile() + ""));
        text_mobile.setText(s.getMobile() + "");
        text_num.setText("" + s.getNum()+"次");
        text_money.setText("" + s.getMoney()+"元");
        if (type == 2) {
            line_money.setVisibility(View.GONE);
        } else {
            line_money.setVisibility(View.VISIBLE);
        }
        text_manager.setText("" + s.getManager());
        text_mobile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DatePhotoUtils.isPhone(s.getMobile() + "")) {
                    DialPhoneDialog.show(CustomerActivity.this,null,s.getMobile()+"");
                } else {
                    com.luck.picture.lib.tools.ToastUtils.s(CustomerActivity.this, "手机号有误");
                }
            }
        });
        helper.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomerDetailsActivity.start(s.getId() + "", type + "",s.getManager_id()+"");
            }
        });
    }

    @Override
    public void fillMuteView(BaseViewHolder helper, CustomerBean.DataBean.ListBean s) {

    }

    @Override
    public void attachActivity(AppCompatActivity activity) {

    }

    @Override
    public void dettachActivity() {

    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(this);
    }

    @Override
    public boolean isMuteAdapter() {
        return false;
    }

    @Override
    public int[] getMuteTypes() {
        return new int[0];
    }

    @Override
    public int[] getMuteLayouts() {
        return new int[0];
    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        if (carrier != null) {
            if (carrier.getType() == 3) {
                if(type_date==1){
                    startTime.setText(carrier.getStarttime().replace("-", "-")+"");
                    begin_time = carrier.getStarttime().replace("-", "-");
                }else{
                    endTime.setText("" + carrier.getStarttime().replace("-", "-"));
                    end_time = carrier.getStarttime().replace("-", "-");
                }
                request(1);
            }
        }
    }

    @OnClick({R.id.start_time, R.id.end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_time://获取验证码
                type_date=1;
                CalendarActivity.start(3);
                break;
            case R.id.end_time://协议
                type_date=2;
                CalendarActivity.start(3);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); //解除注册
    }

}